package com.health.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import com.health.viewscontrols.NovaApplication;
import com.health.tablebean.ARCHIVE_BASEINFO;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;


public class FTPTool {
	private static Dialog progressDialog;
	public static Context context;
	//public static String strWhere = "IDCARD = '" + NovaApplication.userInfo.getIDCARD() + "'";
	private static String dbName;
	public static Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				Toast.makeText(context, "数据上传成功", Toast.LENGTH_LONG).show();
				//上传完数据 修改字段IS_UPDATE
				List<ARCHIVE_BASEINFO> infoList = NovaApplication.fdbmanger.findAll(ARCHIVE_BASEINFO.class);
				for (ARCHIVE_BASEINFO info : infoList) {
					info.setIS_UPDATE("N");
					NovaApplication.fdbmanger.updata(info);
				}
//				String url = GlobalConts.URL_POST +"ehr/uploadFileValidate?fileName=" + dbName;
				String url = GlobalConts.getUrlPost() +"uploadFileValidate?fileName=" + dbName;
				FinalHttp http = new FinalHttp();
				Log.e("url", url);
				http.get(url, new AjaxCallBack<Object>() {

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						// TODO Auto-generated method stub
						super.onFailure(t, errorNo, strMsg);
						Toast.makeText(context, "数据校验失败", 0).show();
					}

					@Override
					public void onSuccess(Object t) {
						// TODO Auto-generated method stub
						super.onSuccess(t);
						Toast.makeText(context, "数据校验成功", 0).show();
						Log.e("返回的数据", t.toString());
//						NovaApplication.userInfo.setIS_UPDATE("N");
//						NovaApplication.fdbmanger.save(NovaApplication.userInfo);
					}
					
				});
				break;
			case 2:
				Toast.makeText(context, "数据上传失败,请检查ftp用户名密码",
						Toast.LENGTH_LONG).show();
				break;
			}
		}

	};

	public static void ftpUpdateDB(Context context) {
		FTPTool.context = context;
		if (GlobalConts.isNetworkAvailable(context)) {
			
			
			try {
				InputStream is = new FileInputStream(
						new File(
								NovaApplication.dbPath));
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					File path = Environment
							.getExternalStorageDirectory();
					String lujing = path.getPath()
							+ "/nova/download/";
					Calendar c = Calendar.getInstance();
					String date = c.get(Calendar.YEAR) + ""
							+ (c.get(Calendar.MONTH) + 1) + ""
							+ c.get(Calendar.DAY_OF_MONTH) + ""
							+ c.get(Calendar.HOUR_OF_DAY) + ""
							+ c.get(Calendar.MINUTE) + ""
							+ c.get(Calendar.SECOND) + "";

					File dir = new File(lujing);
					if (!dir.exists()) {
						dir.mkdirs();
					}
//					SharedPreferences sp = context.getSharedPreferences(
//					GlobalConts.SHAREPREFRENCE_NAME, Activity.MODE_PRIVATE);
					String org_village_id = "v3_"+SPUtil.getStr_jdrno(context);//sp.getString("str_jdrno", "0");
					String addr = BluetoothAdapter.getDefaultAdapter().getAddress(); 
					addr = addr.replace(":", "");
					dbName = org_village_id + "_" +addr+"_"+ date +"_PAD"+ "_ehrapp.db";
					OutputStream os = new FileOutputStream(
							new File(lujing + dbName));
					byte[] buffer = new byte[1024];
					int count = 0;
					while ((count = is.read(buffer)) > 0) {
						os.write(buffer, 0, count);
					}
					os.close();
					is.close();
					// 上传提示
					data_dialog();

				} else {

					Toast.makeText(context,
							"对不起！无数据......", Toast.LENGTH_SHORT)
							.show();
				}
			} catch (IOException e) {
				e.printStackTrace();
				Toast.makeText(context, "对不起！无数据......",
						Toast.LENGTH_SHORT).show();
			}
		
		}else {
			Toast.makeText(context, "请检查网络连接", 0).show();
		}
		
	}
	
	
	protected static void data_dialog() {
		AlertDialog.Builder builder = new Builder(context);
		builder.setMessage("确定要上传数据吗！");
		builder.setTitle("提示");
		builder.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				progressDialog = ProgressDialog.show(context, null,
						"正在上传数据，请稍后...", true, true);
				new Thread() {
					//Calendar c = Calendar.getInstance();

					@Override
					public void run() {
						String ftp = NovaApplication.getFtpAddress();
						String name = NovaApplication.getFtpAccount();
						name = TextUtils.isEmpty(name)?"archivenew":name;
						String password = NovaApplication.getFtpPassword();
						password = TextUtils.isEmpty(password)?"archivenew":password;
						
						Log.w("ftp", ftp);
						Log.w("ftp用户名", name);
						Log.w("ftppassword名", password);
						File path = Environment.getExternalStorageDirectory();
						if (path.exists()) {
							String lujing = path.getPath() + "/nova/download/";
							ftpUpload(ftp, "21", name, password,
									"/", lujing, dbName);
							
						} else {

						}

					}
				}.start();

				dialog.dismiss();

			}
		});
		builder.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String path = Environment.getExternalStorageDirectory().getPath()
						.toString()
						+ "/nova/download/" + dbName;
				File mFile = new File(path);
				mFile.delete();
				dialog.dismiss();
			}
		});
		builder.create().show();
	}
	
	private static String ftpUpload(String url, String port, String username,
			String password, String remotePath, String fileNamePath,
			String fileName) {
		FTPClient ftpClient = new FTPClient();
		FileInputStream fis = null;
		String returnMessage = "0";
		try {
			ftpClient.setConnectTimeout(1000 * 30);
			ftpClient.connect(url, Integer.parseInt(port));
			boolean loginResult = ftpClient.login(username, password);
			int returnCode = ftpClient.getReplyCode();
			if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功
				ftpClient.makeDirectory(remotePath);
				// 设置上传目录
				// 时间获取
				ftpClient.changeWorkingDirectory(remotePath);
				ftpClient.setBufferSize(1024);
				ftpClient.setControlEncoding("UTF-8");
				ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
				ftpClient.enterLocalPassiveMode();
				fis = new FileInputStream(fileNamePath + fileName);
				ftpClient.storeFile(fileName, fis);
				returnMessage = "1"; // 上传成功
				Message msg = Message.obtain();
				msg.what = 1;
				handler.sendMessage(msg);
				//UserCheckTools.check_date(MainActivity.this);
			} else {// 如果登录失败
				returnMessage = "0";
				Message msg = Message.obtain();
				msg.what = 2;
				handler.sendMessage(msg);
				progressDialog.dismiss();
			}

		} catch (IOException e) {
			e.printStackTrace();
			Message msg = Message.obtain();
			msg.what = 2;
			handler.sendMessage(msg);
			progressDialog.dismiss();
		} finally {
			// IOUtils.closeQuietly(fis);
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
				Message msg = Message.obtain();
				msg.what = 2;
				handler.sendMessage(msg);
				progressDialog.dismiss();
			}
		}
		String path = Environment.getExternalStorageDirectory().getPath()
				.toString()
				+ "/nova/download/" + dbName;
		File mFile = new File(path);
		mFile.delete();
		// NotifyParserData(fileName, "0");
		progressDialog.dismiss();
		return returnMessage;

	}
}
